#pragma strict
////////////////////////////////////////////////////////////////////////////////////
///关卡间,摄影机过度.
////////////////////////////////////////////////////////////////////////////////////
var texture:Texture2D;
//黑暗到正常的范围.
var fadeRange:Vector2 = Vector2(-3,0);
// 渐变时间
var fadeInTime:float = 3;
var fadeOutTime:float = 3;
//渐入
var testFadeIn:boolean;
//渐出
var testFadeOut:boolean;
//速度
var speed:float;
//屏幕效果.
var overlay:ScreenOverlay;
var overlayShader:Shader;

var fadeInWhenStart:boolean = true;
var fadeInDelay:float = 0;

var fadeOutWhenStart:boolean;
var fadeOutDelay:float = 3;

var eventReceiver:Transform;
var eventName:String = "OnCameraFadeComplete";

function Start(){
	if(fadeInWhenStart){
		yield WaitForSeconds(fadeInDelay);
		OnFadeIn();
	}
	if(fadeOutWhenStart){
		yield WaitForSeconds(fadeOutDelay);
		OnFadeOut();
	}
}

function Update () {
	if(testFadeIn){
		testFadeIn = false;
		OnFadeIn();
	}
	if(testFadeOut){
		testFadeOut = false;
		OnFadeOut();
	}
}
/* 从左到右.黑到白. */
function OnFadeIn(){
	CheckEffect();
	overlay.intensity = fadeRange.x;
	speed = fadeRange.magnitude / fadeInTime;
	while(overlay.intensity < fadeRange.y){
		overlay.intensity += speed * Time.deltaTime;
		yield;
	}
	overlay.intensity = fadeRange.y;
}
/* 从右到左.白到黑. */
function OnFadeOut(){
	CheckEffect();
	overlay.intensity = fadeRange.y;
	speed = fadeRange.magnitude / fadeOutTime;
	while(overlay.intensity > fadeRange.x){
		overlay.intensity -= speed * Time.deltaTime;
		yield;
	}
	overlay.intensity = fadeRange.x;
}

private function Fade(startValue:float){
	CheckEffect();
	overlay.intensity = startValue;
	speed = fadeRange.magnitude / fadeOutTime;
	while(overlay.intensity > fadeRange.x){
		overlay.intensity -= speed * Time.deltaTime;
		yield;
	}
	overlay.intensity = fadeRange.x;
}

private function CheckEffect(){
	overlay = GetComponent.<ScreenOverlay>();
	if(! overlay)
		overlay = gameObject.AddComponent.<ScreenOverlay>();
	if(! overlay.overlayShader){
		overlay.overlayShader = Shader.Find("Hidden/BlendModesOverlay");
		overlay.overlayShader = overlayShader;
	}
	overlay.texture = texture;
	// overlay.blendMode = ScreenOverlay.OverlayBlendMode.AddSub;
	overlay.intensity = fadeRange.x;
}

function FadeComplete(){
	if(eventReceiver){
		eventReceiver.SendMessage(eventName,overlay.intensity);
	}
}

